'use strict';

const Service = require('egg').Service;


class PaymentService extends Service {
  
  async postPaymentPay(query) {
    const ctx = this.ctx;

    const [ orderDetail = {} ] = await ctx.service.order.getOrderDetail({
      orderId: query.orderId,
      userId: query.userId,
    });


    if (orderDetail.state === 'NOPAY') {
      const orderQuery = { _id: query.orderId };
      const result = await ctx.model.Order.findOneAndUpdate(orderQuery, { state: 'PAY' });

      const expertQuery = { _id: orderDetail.expert_id };
      const e = await this.ctx.model.Expert.findOne(expertQuery).lean();
      
      if (e && e.help_total_count && typeof(e.help_total_count) === 'number') {
        await this.ctx.model.Expert.update(expertQuery, { $inc: { help_total_count: 1 } });
      } else if (e)  {
        await this.ctx.model.Expert.update(expertQuery, { help_total_count: 1 });
      }
      
      return [ { state: 'PAY', result } ];
    }

    return [ ];
  }

  async postPaymentDone(query) {
    const ctx = this.ctx;

    const [ orderDetail = {} ] = await ctx.service.order.getOrderDetail({
      orderId: query.orderId,
      userId: query.userId,
    });
    
    if (orderDetail.state === 'PAY') {
      const orderQuery = { _id: query.orderId };
      const result = await ctx.model.Order.findOneAndUpdate(orderQuery, { state: 'DONE' });
      return [ { state: 'DONE', result } ];
    }

    return [ ];
  }

}

module.exports = PaymentService;

